package com.lin.reggie.controller;

import com.lin.reggie.common.R;
import com.lin.reggie.entity.ShoppingCart;
import com.lin.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {

    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;

    @RequestMapping("/add")
    public R<ShoppingCart>addShoppingCart(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        //获取登录人id
        Long id = (Long) session.getAttribute("user");
        //把登录人id存入购物车
        shoppingCart.setUserId(id);
        ShoppingCart addShoppingCart = shoppingCartService.addCart(shoppingCart);
        return R.success(addShoppingCart);
    }
    @GetMapping("/list")
    public R<List<ShoppingCart>>list(HttpSession session){
        //获取登录者
        Long userId = (Long) session.getAttribute("user");
        //2.根据当前登录者查看购物车
        List<ShoppingCart> cartByUserId = shoppingCartService.findCartByUserId(userId);
        return R.success(cartByUserId);
    }
    @RequestMapping("/clean")
    public R<String>deleteShoppingCart(HttpSession session){
        //获取登录者
        Long id = (Long) session.getAttribute("user");
        shoppingCartService.deleteShopp(id);
        return R.success("清空购物车成功");
    }
    @RequestMapping("/sub")
    public R<ShoppingCart>deleteShopping(@RequestBody ShoppingCart shoppingCart,HttpSession session){
        //获取登录者
        Long id = (Long) session.getAttribute("user");
        shoppingCart.setUserId(id);
        ShoppingCart cart = shoppingCartService.delete(shoppingCart);
        return R.success(cart);
    }
}
